/*
 * @Author: szx
 * @Date: 2022-06-08 11:47:12
 * @LastEditTime: 2022-06-08 11:55:06
 * @Description:
 * @FilePath: \leetcode\面试题\16\13\13.js
 */
/**
 * @param {number[]} square1
 * @param {number[]} square2
 * @return {number[]}
 */
var cutSquares = function (square1, square2) {
    // 圆心坐标
    const x1 = square1[0] + square1[2] / 2,
        y1 = square1[1] + square1[2] / 2,
        x2 = square2[0] + square2[2] / 2,
        y2 = square2[1] + square2[2] / 2;
    if (x1 == x2) {
        // 垂直x轴，交点在上下边
        return [x1, Math.min(square1[1], square2[1]), x1, Math.max(square1[1] + square1[2], square2[1] + square2[2])];
    }
    // 有斜率的情况下
    const k = (y2 - y1) / (x2 - x1),
        b = y1 - k * x1;
    // 斜率的绝对值小于1，那么交点就在左右两边
    if (Math.abs(k) <= 1) {
        // 交点在左右边
        const xmin = Math.min(square1[0], square2[0]),
            xmax = Math.max(square1[0] + square1[2], square2[0] + square2[2]);
        return [xmin, k * xmin + b, xmax, k * xmax + b];
    }
    // 斜率的绝对值大于1，交点在上下两边
    const ymin = Math.min(square1[1], square2[1]),
        ymax = Math.max(square1[1] + square1[2], square2[1] + square2[2]),
        ans = [(ymin - b) / k, ymin, (ymax - b) / k, ymax];
    // 重排序，保证第一个点在左边，斜率为正和负，左边的点可能是上面和下面两种情况
    if (ans[0] < ans[2]) return ans;
    return [ans[2], ans[3], ans[0], ans[1]];
};
